import Vue from 'vue'
import VueRouter from 'vue-router'
/* 导入静态路由文件 */
import staticFile from './static'
/* 导入vuex */
import store from '@/store'
import Message from 'element-ui'
Vue.use(VueRouter)

const router = new VueRouter({
  mode: "history",
  /* 键值对 */
  routes: staticFile
})

/* 路由导航守卫只触发一次 */
let flag = true;
/* 设置全局路由导航守卫 */
router.beforeEach(async (to, from, next) => {
  if (to.path !== '/login') {
    //登录数据
    var user = store.state.userObj.token
    if (!user) {
      Message({
        message: '请先登录',
        type: 'warning'
      })
      next('/login');
    } else {
      /* 有token并且非登录页面，需要将vuex存储的路由信息追加到router对象上 */
      var routeList = await store.state.routeModule.route
      if (flag && routeList.length != 0) {
        routeList.forEach(item => {
          item.component = getComponents(item.name);
          router.addRoute('Home', item)
        })
        // console.log(router.getRoutes())
        flag = false;
        next({
          ...to,
          replace: true
        })
      } else {
        next();
      }
    }
  } else {
    next();
  }
})

/* 封装组件配置路径 */
function getComponents(path) {
  return () => import(`@/components/home/${path}`)
}
export default router
